package io.renren.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.annotation.Login;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.utils.Result;
import io.renren.modules.health.dto.HmSportDTO;
import io.renren.modules.health.dto.HmSportRecord2DTO;
import io.renren.modules.health.dto.HmSportRecordDTO;
import io.renren.modules.health.entity.HmSportRecordEntity;
import io.renren.modules.health.service.HmSportRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 客户运动记录
 *
 * @author
 * @since 1.0.0 2024-04-03
 */
@RestController
@RequestMapping("api/hmsportrecord")
@Api(tags = "客户运动记录")
public class HmSportRecordController {
    @Autowired
    private HmSportRecordService hmSportRecordService;

    @Login
    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType = "String")
    })
    public Result<PageData<HmSportRecord2DTO>> page(@ApiIgnore @RequestParam Map<String, Object> params) {
        if (params.get("cusId") != null) params.put("cusId", Long.parseLong((String) params.get("cusId")));
        params.put("recordDate", LocalDate.now());

        PageData<HmSportRecordDTO> page = hmSportRecordService.page(params);
        PageData<HmSportRecord2DTO> record2DTOPageData = new PageData<HmSportRecord2DTO>(page.getList().stream().map(f -> {
            HmSportRecord2DTO hmSportRecord2DTO = new HmSportRecord2DTO();
            BeanUtils.copyProperties(f, hmSportRecord2DTO);
            hmSportRecord2DTO.setSports(JSON.parseObject(f.getSports(), new TypeReference<List<HmSportDTO>>() {
            }));
            return hmSportRecord2DTO;
        }).collect(Collectors.toList()), page.getTotal());
        return new Result<PageData<HmSportRecord2DTO>>().ok(record2DTOPageData);
    }

    @Login
    @PostMapping
    @ApiOperation("保存")
    public Result save(@RequestBody HmSportRecord2DTO dto) {
        dto.setRecordDate(new Date(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toEpochSecond()));
        HashMap<String, Object> param = new HashMap<>();
        param.put("cusId", dto.getCusId());
        param.put("recordDate", LocalDate.now());
        PageData<HmSportRecordDTO> pageData = hmSportRecordService.page(param);
        if (pageData.getTotal() > 0) {
            List<HmSportDTO> sportDTOS = JSON.parseObject(pageData.getList().get(0).getSports(), new TypeReference<List<HmSportDTO>>() {
            });
            if (dto.getSports().get(0).getDuration() == 0) sportDTOS.removeIf(sport -> dto.getSports().get(0).getId().equals(sport.getId()));
            else {
                if (sportDTOS.stream().noneMatch(sport -> dto.getSports().get(0).getId().equals(sport.getId()))) {
                    sportDTOS.addAll(dto.getSports());
                } else {
                    sportDTOS.stream()
                            .filter(sport -> dto.getSports().get(0).getId().equals(sport.getId()))
                            .findFirst()
                            .get()
                            .setSportTrophy(dto.getSports().get(0).getSportTrophy())
                            .setDuration(dto.getSports().get(0).getDuration());

                }
            }

            hmSportRecordService.update(new HmSportRecordEntity().setSports(JSON.toJSONString(sportDTOS)),
                    new QueryWrapper<HmSportRecordEntity>()
                            .eq("cus_id", dto.getCusId())
                            .eq("record_date", LocalDate.now()));
        } else {
            hmSportRecordService.insert(
                    new HmSportRecordEntity()
                            .setCusId(dto.getCusId())
                            .setSports(JSON.toJSONString(dto.getSports()))
            );

        }

        return new Result();
    }

}